package com.atguigu.gmall.activity.congtroller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.redisson.misc.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author atguigu-mqx
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;

    //  /api/activity/seckill/findAll
    @GetMapping("findAll")
    public Result findAll(){
        //  调用方法
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();
        //  返回数据
        return Result.ok(seckillGoodsList);
    }

    //  /api/activity/seckill/getSeckillGoods/{skuId}
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId){
        //  调用方法
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        //  返回数据
        return Result.ok(seckillGoods);
    }

    //  获取下单码！
    //  http://api.gmall.com/api/activity/seckill/auth/getSeckillSkuIdStr/22
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //  生成下单码！
        String userId = AuthContextHolder.getUserId(request);
        //  获取秒杀对象！
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        if (seckillGoods!=null){
            //  在秒杀开始之后，结束之前生成下单码！
            Date currentTime = new Date();
            if (DateUtil.dateCompare(seckillGoods.getStartTime(),currentTime) &&
                DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                //  对userId 进行md5加密
                return Result.ok(MD5.encrypt(userId));
            }
        }
        //  返回数据！
        return Result.fail().message("获取下单码失败！");
    }

    //  秒杀下单：/api/activity/seckill/auth/seckillOrder/{skuId}?skuIdStr=xxx
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  校验下单码！
        String skuIdStr = request.getParameter("skuIdStr");
        //  获取用户Id 再次生成下单码！
        String userId = AuthContextHolder.getUserId(request);
        //  校验失败！
        if (!skuIdStr.equals(MD5.encrypt(userId))){
            //  返回！
            //  return Result.fail().message("下单码校验失败，非法秒杀!");
            return Result.build(null,ResultCodeEnum.SECKILL_ILLEGAL);
        }
        //  校验 状态位！ skuId:status  status 0 or 1
        String status = (String) CacheHelper.get(skuId.toString());

        if("0".equals(status)){
            //  售罄
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
            //  return Result.fail().message("已售罄");
        }else if (StringUtils.isEmpty(status)){
            //  return Result.fail().message("非法请求");
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }else {
            //  说明可以抢购！ 记录哪个用户抢购哪个商品，并放入队列！
            UserRecode userRecode = new UserRecode();
            //  赋值
            userRecode.setUserId(userId);
            userRecode.setSkuId(skuId);
            //  发送消息到队列！
            this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,MqConst.ROUTING_SECKILL_USER,userRecode);
            //  正常返回！
            return Result.ok();
        }
    }

    //  检查轮询接口：
    //  /api/activity/seckill/auth/checkOrder/{skuId}
    @GetMapping("auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  判断用户是否存在，则必须有个啥？ userId
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层
        return  this.seckillGoodsService.checkOrder(skuId,userId);
    }

    //  秒杀订单！
    @GetMapping("/auth/trade")
    public Result authTrade(HttpServletRequest request){
        //  声明一个map
        HashMap<String, Object> map = new HashMap<>();

        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  写个service 方法！
        //  获取收货地址列表！
        List<UserAddress> userAddressList = this.userFeignClient.findUserAddressListByUserId(userId);

        //  detailArrayList 秒杀商品明细！
        //  确定数据类型！ hash key = seckill:orders  field = userId  value = orderRecode
        //  this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).put(userId,orderRecode);
        OrderRecode orderRecode = (OrderRecode) this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).get(userId);
        if (orderRecode==null){
            return Result.fail().message("预下单中没有数据!");
        }
        //  用户秒杀的商品！
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();
        //  detailArrayList 订单明细！
        List<OrderDetail> detailArrayList = new ArrayList<>();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        //  price 原价： cost_price ： 秒杀价格
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        //  放入集合
        detailArrayList.add(orderDetail);

        //  价格：
        //        OrderInfo orderInfo = new OrderInfo();
        //        orderInfo.setOrderDetailList(detailArrayList);
        //        orderInfo.sumTotalAmount();
        //  存储数据
        //  userAddressList detailArrayList totalAmount totalNum
        map.put("userAddressList",userAddressList);
        map.put("detailArrayList",detailArrayList);
        //  秒杀就一件商品！总价格就是单个商品的秒杀价！
        map.put("totalAmount",seckillGoods.getCostPrice());
        map.put("totalNum",orderRecode.getNum());
        //  返回map 数据
        return Result.ok(map);

    }

    //  提交订单 ： /auth/submitOrder
    //  接收到前端传递的数据：Json ---> JavaObject
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){

        //  获取用户Id，赋值给orderInfo 对象！ 提交订单的时候，前端页面并没有userId
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //  远程调用订单微服务中的提交订单方法！ 将数据保存到orderInfo  +  orderDetai  mysql！
        Long orderId = this.orderFeignClient.submitOrder(orderInfo);
        if(orderId==null){
            return Result.fail().message("提交订单失败!");
        }

        //  如果已经真正下过订单了，则预下单就不需要了！
        //  this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).hasKey(userId);
        //  hdel key field
        this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);

        //  同时还需要将真正下单数据保存到缓存一份！
        //  Hash key = RedisConst.SECKILL_ORDERS_USERS field = userId  value = orderId
        this.redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId,orderId.toString());

        //  返回数据！ window.location.href = 'http://payment.gmall.com/pay.html?orderId=' + response.data.data
        return Result.ok(orderId);
    }


}
